package com.manner.groupon.utils;

import cn.hutool.json.JSONUtil;
import com.manner.groupon.properties.WxAppletProperties;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import javax.annotation.Resource;
import java.net.URI;

@Component
public class WxMiniUtil {

    /**
     * 前缀URL
     */
    public static final String PREV_URL = "https://api.weixin.qq.com/";

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private WxAppletProperties wxAppletProperties;

    private static final String GRANT_TYPE = "client_credential";

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    class AccessToken {

        private String access_token;

        private Integer expires_in;
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    class RequestPhoneParam {

        private String code;
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    class UserPhone {

        private Integer errcode;

        private String errMsg;

        private PhoneInfo phone_info;

        @Data
        @AllArgsConstructor
        @NoArgsConstructor
        class PhoneInfo {

            private String phoneNumber;

            private String purePhoneNumber;
        }
    }


    /**
     * 获取令牌
     *
     * @return
     */
    private String getToken() {

        URI targetUrl = UriComponentsBuilder.fromUriString(PREV_URL + "cgi-bin/token")
                .queryParam("appid", wxAppletProperties.getAppid())
                .queryParam("secret", wxAppletProperties.getSecret())
                .queryParam("grant_type", GRANT_TYPE)
                .build()
                .toUri();

        String json = restTemplate.getForObject(targetUrl, String.class);

        //转换
        AccessToken token = JSONUtil.toBean(json, AccessToken.class);

        return token.getAccess_token();
    }

    /**
     * 获取用户手机号
     *
     * @param code 前端小程序令牌
     * @return
     */
    public String getPhone(String code) {
        RequestPhoneParam requestPhoneParam = new RequestPhoneParam(code);
        //转为JSON
        String requestJson = JSONUtil.toJsonStr(requestPhoneParam);
        //获取令牌
        String token = getToken();
        //构建请求URL
        URI uri = UriComponentsBuilder.fromUriString(PREV_URL + "wxa/business/getuserphonenumber")
                .queryParam("access_token", token)
                .build()
                .toUri();
        //请求获取数据
        String json = restTemplate.postForObject(uri, requestJson, String.class);

        UserPhone userPhone = JSONUtil.toBean(json, UserPhone.class);

        //返回数据
        return userPhone.getPhone_info().getPurePhoneNumber();
    }

}
